/**
 * @author:linjiye
 * @date: 2024/12/25
 * @desc:
 **/

import {Image, StyleSheet, Text, TextInput, TouchableOpacity, View} from 'react-native'
import React, {useCallback, useEffect, useState} from 'react'
import PageScrollView from "@/components/PageScrollView";
import {FcView} from "@/components/FcView";
import PageFormBtn from "@/components/PageFormBtn";
import TabCard from "@/components/TabCard";
import FormTitle from "@/components/FormTitle";
import FcButton from "@/components/FcButton";
import {aiOriginalityData} from "@/utils/data"
import {Flex} from "@ant-design/react-native";
import RequiredIcon from "@/components/RequiredIcon";
import {LinearGradient} from "expo-linear-gradient";
import Slider from '@react-native-community/slider';
import FcSlider from "@/components/FcSlider";
import FcModal from '../FcModal';
import {router} from "expo-router";
import NoData from '../NoData';
import {
    useGetItemListQuery,
    useGetParentListQuery,
    useGetTemplateListQuery, useProfitModelInfoMutation
} from "@/store/api/aiOriginality/aiOriginalityApi";
import SdsrPage1 from "@/components/aiOriginality/SdsrPage1";
import {useDispatch, useSelector} from "react-redux";
import {set_SYZLParams} from "@/store/reducer/aiOriginality/aiOriginalitySlice";
import useGetStorage from "@/hooks/useGetStorage";
import useSetStorage from "@/hooks/useSetStorage";
import FcSearch from "@/components/FcSearch";

type Props = {}

const SYZLKPage = ({listData, onGetParams}: Props) => {
    const [typeList, setTypeList] = useState([
        {
            name: '提供产品',
            id: 1,
        }, {
            name: '提供服务',
            id: 2
        }
    ])
    const [typeId, setTypeId] = useState(typeList[0]?.id)
    const [productGroupItem, setProductGroupItem] = useState({})
    const [productNameItem, setProductNameItem] = useState({})
    const [ylItem, setYlItem] = useState({})
    const [list, setList] = useState(listData)
    const [openProductGroup, setOpenProductGroup] = useState(false)
    const [openProduct, setOpenProduct] = useState(false)
    const [openProductYL, setOpenProductYL] = useState(false)
    const [groupList, setGroupList] = useState([])
    const [productList, setProductList] = useState([])
    const [ylList, setYlList] = useState([])
    const [pressedIndex, setPressedIndex] = useState(-1);

    const [groupSearchText, setGroupSearchText] = useState('')
    const [productSearchText, setProductSearchText] = useState('')

    const {data:groupResData,isSuccess:groupSuccess, refetch:groupRefetch}= useGetParentListQuery?.({
        type: typeId,
        name: groupSearchText
    })
    const {data:productResData,isSuccess:productSuccess, refetch:productRefetch}= useGetItemListQuery?.({
        parentId: productGroupItem?.id,
        name: productSearchText
    })
    const [profitModelInfoFun] = useProfitModelInfoMutation?.()

    const [params,setParams] = useState({
        // vars: [],
        // articlesNum: 1,
        // disable: true
    })

    const dispatch = useDispatch()
    let p = useSelector(state => state.aiOriginality.SYZLParams)
    console.log(p,'--------====------------');


    useEffect(() => {
        useGetStorage('SYZLKPageData').then((res) => {
            if (res) {
                setTypeId(res.typeId || typeList[0]?.id)
                setProductGroupItem(res.productGroupItem || {})
                setProductNameItem(res.productNameItem || {})
                setYlItem(res.ylItem || {})

                dispatch(set_SYZLParams({
                    ...params,
                    profitModelId: res.ylItem?.id || '',
                    groupId: res.productGroupItem?.id || '',
                    // templateId: res.productNameItem?.id || '',
                }))
            }

        })
    }, []);

    useEffect(() => {
        handleBigMenu(list[0])

        if (groupSuccess) {
            setGroupList(groupResData.result || [])
            // setProductGroupItem(groupResData.result[0])
            // productRefetch()
        }
        if (productSuccess) {
            setProductList(productResData.result || [])
            // setProductNameItem(productResData.result[0])
            // getProfitModelInfoFun(productResData.result[0].id)
        }
        if(p) setParams(p)
    },[groupSuccess,groupResData,productSuccess,productResData,p])

    const getProfitModelInfoFun = (id) => {
        profitModelInfoFun({
            id
        }).then(res => {
            if (res?.data?.code === 200) {
                setYlList(res?.data?.result || [])
            }
        })
    }

    const handleProduct = (val) => {
        setTypeId(val.id)
        setProductGroupItem({})
        setProductNameItem({})
        setYlItem({})

        dispatch(set_SYZLParams({
            ...params,
            groupId: '',
            profitModelId: ''
        }))

        useGetStorage('SYZLKPageData').then((res) => {
            let obj = res ? res : {}
            obj.typeId = val.id
            obj.productGroupItem = {}
            obj.productNameItem = {}
            obj.ylItem = {}
            useSetStorage('SYZLKPageData', obj)
        })
    }


    const handleBigMenu = (val) => {
        // setBigMenuId(val.id)
        // setSmallMenu(val.list)
        // setSmallMenuId(val.list[0].id)
    }

    const getProductGroup = (val) => {
        dispatch(set_SYZLParams({
                ...params,
                groupId: val.id
            }))

        setProductGroupItem(val)
        setProductNameItem({})
        setYlItem({})
        setOpenProductGroup(false)

        useGetStorage('SYZLKPageData').then((res) => {
            let obj = res ? res : {}
            obj.productGroupItem = val
            obj.productNameItem = {}
            obj.ylItem = {}
            useSetStorage('SYZLKPageData', obj)
        })

        productRefetch()
    }

    const getProductName = (val) => {
        setProductNameItem(val)
        setYlItem({})
        setOpenProduct(false)
        getProfitModelInfoFun(val.id)

        useGetStorage('SYZLKPageData').then((res) => {
            let obj = res ? res : {}
            obj.productNameItem = val
            obj.ylItem = {}
            useSetStorage('SYZLKPageData', obj)
        })
    }

    const getProductYL = (val) => {
        dispatch(set_SYZLParams({
            ...params,
            profitModelId: val.id
        }))
        setYlItem(val)
        setOpenProductYL(false)

        useGetStorage('SYZLKPageData').then((res) => {
            let obj = res ? res : {}
            obj.ylItem = val
            useSetStorage('SYZLKPageData', obj)
        })
    }

    const handleProductGroup = () => {
        setGroupSearchText('')
        setOpenProductGroup(true)
        groupRefetch()
    }

    const handleProdut = () => {
        setProductSearchText('')
        setOpenProduct(true)
        productRefetch()
    }

    const getParams = useCallback((newData) => {
        console.log(newData);
        // setParams(newData)
        handleSetParams(newData)
    },[])

    const handleSetParams = (val) => {
        console.log(val);
    }

    // @ts-ignore
    return (
        <FcView style={styles.container}>

            <FormTitle style={{paddingHorizontal: 16}} isLeftIcon title='选私有库关联产品'
                       titleHint='选私有库关联产品'/>
            <Flex wrap='wrap' style={styles.big_menu}>
                {typeList?.map((item, index) =>
                    <FcButton
                        key={index}
                        onClick={() => handleProduct(item)}
                        type={typeId === item.id ? 'txtBK' : 'default'}
                        style={[styles.big_menu_item]}
                        itemStyle={{width: '100%', height: '100%'}}
                        textName={item.name} borderWidth={1}></FcButton>
                )}
            </Flex>

            <View style={{paddingHorizontal: 16}}>
                <FormTitle style={{marginTop: 8}} title='选产品分组'/>
                <TouchableOpacity onPress={() => handleProductGroup(true)}>
                    <View style={styles.item_wrap}>
                        <Text
                            style={[productGroupItem.name ? styles.item_label : styles.item_hint]}>{productGroupItem.name || '请选择'}</Text>
                        <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#79797A'}}>&#xe609;</Text>
                    </View>
                </TouchableOpacity>

                <FormTitle style={{marginTop: 8}} title='选产品名称'/>
                <TouchableOpacity onPress={() => handleProdut()}>
                    <View style={styles.item_wrap}>
                        <Text
                            style={[productNameItem.name ? styles.item_label : styles.item_hint]}>{productNameItem.name || '请选择'}</Text>
                        <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#79797A'}}>&#xe609;</Text>
                    </View>
                </TouchableOpacity>

                <FormTitle style={{marginTop: 8}} title='选盈利模式'/>
                <TouchableOpacity onPress={() => setOpenProductYL(true)}>
                    <View style={styles.item_wrap}>
                        <Text style={[ylItem.typeName ? styles.item_label : styles.item_hint]}>{ylItem.typeName || '请选择'}</Text>
                        <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#79797A'}}>&#xe609;</Text>
                    </View>
                </TouchableOpacity>
            </View>

            <SdsrPage1 onGetParams={getParams}></SdsrPage1>

            <FcModal
                isOpen={openProductGroup}
                onFcModalClose={() => setOpenProductGroup(false)}
                titleText='选择产品分组'
                header={<FcSearch searchText={groupSearchText} onSearch={(val) => setGroupSearchText(val)}/>}
                titleBottomBorderWidth={0}
            >
                <View>
                    {groupList.map((item, index) => (
                        <TouchableOpacity key={index}
                                          activeOpacity={1}
                                          style={[styles.modal_item_text, pressedIndex === index && styles.modal_item_pressed]}
                                          onPress={() => getProductGroup(item)}
                                          onPressIn={() => setPressedIndex(index)}
                                          onPressOut={() => setPressedIndex(-1)}
                        >
                            <Text numberOfLines={1} ellipsizeMode="tail">{item.name}</Text>
                        </TouchableOpacity>
                    ))}
                    {groupList?.length <= 0 &&
                        <View style={{
                            flexDirection: 'column',
                            alignItems: 'center',
                            justifyContent: 'center',
                            paddingTop: 60,
                            paddingBottom: 120
                        }}>
                            <NoData hintText='暂无分组'/>
                        </View>
                    }
                </View>
            </FcModal>
            <FcModal
                isOpen={openProduct}
                onFcModalClose={() => setOpenProduct(false)}
                titleText='选择产品名称'
                header={<FcSearch searchText={productSearchText} onSearch={(val) => setProductSearchText(val)}/>}
                titleBottomBorderWidth={0}
            >
                <View>
                    {productList.map((item, index) => (
                        <TouchableOpacity key={index}
                                          activeOpacity={1}
                                          style={[styles.modal_item_text, pressedIndex === index && styles.modal_item_pressed]}
                                          onPress={() => getProductName(item)}
                                          onPressIn={() => setPressedIndex(index)}
                                          onPressOut={() => setPressedIndex(-1)}
                        >
                            <Text numberOfLines={1} ellipsizeMode="tail">{item.name}</Text>
                        </TouchableOpacity>
                    ))}
                    {productList?.length <= 0 &&
                        <View style={{
                            flexDirection: 'column',
                            alignItems: 'center',
                            justifyContent: 'center',
                            paddingTop: 60,
                            paddingBottom: 120
                        }}>
                            <NoData hintText='暂无产品'/>
                        </View>
                    }
                </View>
            </FcModal>
            <FcModal
                isOpen={openProductYL}
                onFcModalClose={() => setOpenProductYL(false)}
                titleText='选择盈利模式'
                titleBottomBorderWidth={0}
            >
                <View>
                    {ylList.map((item, index) => (
                        <TouchableOpacity key={index}
                                          activeOpacity={1}
                                          style={[styles.modal_item_text, pressedIndex === index && styles.modal_item_pressed]}
                                          onPress={() => getProductYL(item)}
                                          onPressIn={() => setPressedIndex(index)}
                                          onPressOut={() => setPressedIndex(-1)}
                        >
                            <Text numberOfLines={1} ellipsizeMode="tail">{item.typeName}</Text>
                        </TouchableOpacity>
                    ))}
                    {ylList?.length<=0 &&
                        <View style={{flexDirection: 'column',alignItems: 'center',justifyContent: 'center',paddingTop: 30,paddingBottom: 60}}>
                            <NoData hintText='暂无盈利模式资料' />
                            <FcButton
                                onClick={() => router.navigate(`/aiFeeding`)}
                                type='BjJB'
                                colors={['#6989FF','#C65EFD']}
                                style={{width: 144,height: 32,justifyContent: 'center'}}
                                itemStyle={{borderRadius: 8}}
                                textName='去私有化资料新增'></FcButton>
                        </View>
                    }
                </View>
            </FcModal>
        </FcView>
    )
}

export default SYZLKPage

const styles = StyleSheet.create({
    container: {
        // flex: 1,
        // justifyContent: "center",
        // alignItems: "center",
        backgroundColor: 'white',
        borderBottomLeftRadius: 8,
        borderBottomRightRadius: 8,
        paddingBottom: 16
    },
    big_menu: {
        paddingHorizontal: 4,
        display: "flex",
        flexWrap: "wrap",
        flexDirection: "row",
    },
    big_menu_item: {
        width: 100,
        height: 40,
        lineHeight: 40,
        borderRadius: 8,
        marginHorizontal: 8,
        marginBottom: 8
    },
    small_menu: {
        paddingTop: 20,
        borderStyle: 'dashed',
        borderTopWidth: 1,
        borderColor: 'rgba(0, 0, 0, 0.1)',
        marginHorizontal: 16,
        marginTop: 12
    },
    small_menu_item: {
        paddingHorizontal: 10,
        paddingVertical: 5,
        borderRadius: 20,
        backgroundColor: '#F1F2F4',
        marginHorizontal: 8,
        marginBottom: 8,
        color: '#79797A'
    },
    small_menu_active: {
        color: '#2856FF',
        backgroundColor: 'rgba(40, 86, 255, 0.1)'
    },
    input_wrap: {
        flexDirection: 'row',
        alignItems: "center",
        height: 56,
        borderRadius: 10,
        paddingHorizontal: 12,
        backgroundColor: '#F1F2F4',
        marginBottom: 16
    },
    input_label: {
        fontSize: 17,
        color: 'rgba(0,0,0,0.9)',
        flexDirection: 'row',
        alignItems: "center",
        marginRight: 10
    },
    input_val: {
        fontSize: 17,
        color: 'rgba(0,0,0,0.3)',
        flex: 1,
        height: '100%'
    },
    slider_wrap: {
        flexDirection: "row",
        alignItems: "center",
    },
    slider_input: {
        width: 56,
        height: 32,
        textAlign: "center",
        borderRadius: 8,
        backgroundColor: '#F1F2F4'
    },
    slider_txt: {
        marginLeft: 8,
        fontSize: 14,
        color: 'rgba(0,0,0,0.5)'
    },

    item_wrap: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: 'space-between',
        height: 56,
        paddingHorizontal: 12,
        backgroundColor: '#F1F2F4',
        borderRadius: 8
    },
    item_label: {
        fontSize: 17,
        color: 'rgba(0,0,0,0.9)'
    },
    item_hint: {
        fontSize: 17,
        color: 'rgba(0,0,0,0.3)'
    },
    modal_item_text: {
        marginHorizontal: 16,
        height: 56,
        alignItems: 'center',
        justifyContent: 'center',
        borderBottomColor: 'rgba(0,0,0,0.05)',
        borderBottomWidth: 1,
        fontSize: 17,
        color: 'rgba(0,0,0,0.9)'
    },
    modal_item_pressed: {
        backgroundColor: 'rgba(0,0,0,0.05)'
    }
})